﻿/* GoogleCalculatorAction.cs
 *
 * Shuriken is the legal property of its developers. Please refer to the
 * COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Web; 

namespace GoogleCalculator
{
    public class GCalc
    {
        private const string watermark = @"/images/calc_img.gif";
        private const string start_html = "<h2 class=r style=\"font-size:138%\"><b>";
        private const string end_html = @"</b></h2>";

        public string Calculate(string query)
        {
            try
            {
                string query_url = FormatQueryString(query);
                string html = ExecuteCalculation(query_url);

                return ExtractResult(html);
            }
            catch (Exception excp)
            {
                return "Problem: " + excp.Message;
            }

        }

        private string ExtractResult(string html)
        {
            if (html.Contains(watermark))
            {
                int start = html.IndexOf(start_html) + start_html.Length;
                int end = html.IndexOf(end_html);

                string reply = html.Substring(start, end - start);
                return reply; 
            }

            return "Invalid Expression"; 
        }

        /// <summary>
        /// Creates the encoded query url 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private string FormatQueryString(string query)
        {
            string prefix = @"http://www.google.com/search?q=";
            return prefix + HttpUtility.UrlEncode(query);
        }

        private string ExecuteCalculation(string qstring)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            string html = client.DownloadString(qstring);

            return html; 
        }
    }
}
